package com.shijunhao.graduation.service.system.impl;

import com.shijunhao.graduation.domain.entity.OrgUser;
import com.shijunhao.graduation.domain.entity.SystemDictItem;
import com.shijunhao.graduation.enums.DictCode;
import com.shijunhao.graduation.service.system.IOrgUserService;
import com.shijunhao.graduation.service.system.ISystemDictItemService;
import com.shijunhao.graduation.service.system.ISystemDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: shijunhao
 * @date: 2022/3/3 11:24
 * @description:
 */
@Component
public class UserDetailServiceImpl implements UserDetailsService {

    private final IOrgUserService orgUserService;
    private final ISystemDictService dictService;

    @Autowired
    public UserDetailServiceImpl(IOrgUserService orgUserService, ISystemDictService dictService) {
        this.orgUserService = orgUserService;
        this.dictService = dictService;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        OrgUser orgUser = orgUserService.loadUserByName(s);
        if (orgUser == null)
            throw new UsernameNotFoundException("未找到该用户信息：" + s);
        if(!orgUser.getEnable())
            throw new BadCredentialsException("用户已被禁用：" + s);
        //映射权限名称
        List<SystemDictItem> roles = dictService.loadByCode(DictCode.ROLE.getCode()).getDictItems();
        Map<Integer,String> map = new HashMap<>();
        for(SystemDictItem role:roles){
            map.put(role.getDictValue(),role.getDictLabel());
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_" + map.get(orgUser.getRole())));

        return new User(orgUser.getUsername(),orgUser.getPassword(),orgUser.getEnable(),true,true,true,authorities);
    }

}
